<template>
  <view class="container" >
  <view class="login-container">
    <!-- 提示登录的图标 -->
    <image src="../../static/img/logo.png" class="logo" mode="heightFix"></image>
    <uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
    <!-- 登录按钮 -->
    <button class="btn" hover-class="none" @click="getUserInfo">
    	<image src="../../static/img/wx.png" mode="widthFix"></image>微信登录
    </button>
    <!-- 可以从 @getuserinfo 事件处理函数的形参中，获取到用户的基本信息 -->
    <!-- <button type="primary" class="btn-login"  @click="getUserInfo">一键登录</button> -->
    <!-- 登录提示 -->
    <view class="userBook">登录享受更多权益</view>
   
   </view>
   </view>
 <!--  <view v-else>
  <button class="btn" hover-class="none" >
  	<image src="../../static/img/wx.png" mode="widthFix"></image>微信登录
  </button>
   </view>> -->
  
</template>

<script>
  // 1. 按需导入 mapMutations 辅助函数
  import { mapMutations,mapState } from 'vuex'
  
  export default {
    name:"my-login",
    data() {
      return { 
        appcret:{},
        getCouldUser:{token:''},
        user:{token:'获取失败',
              nickName:'',
              count: 0 },
        userinfo: {},
        getCouldUser1 :{},
        code:'',  
        openidNumb: {},
        openidNumb3: { openid:'1111'},
        xinqiuList : {  
    "code": 2,
    "msg": "success",
    "time": 1649939724,
    "data": {
        "blink_box_ball": {
            "list": [  ],
            "total": 205,
            "dismantle_price": "0.1"
        },
        "sitename": "超越盲盒",
        "user": "",
        "webinfo": {
            "wxappid": "wx228b8b929bee7d05",
            "wxlogocallbackurl": "",
            "open_wx_login": "1"
        },
        "intro": "",
        "index_gg": "133333",
        "tags": [
            "享高佣",
            "",
            "一句话介绍"
        ]
    }
},
      };
    },
    computed:{
      ...mapState('m_user', ['token']),
      ballList(){
      	return this.info ? this.info.blink_box_ball.list : [];
      },
      ...mapState('m_user',['redirectInfo'])
    },
    onLoad(e) {
      
   
   this.getAppAndScrect()
      this.getData()
      
     
      
    },onShow(){
	
		},
    methods: {
      //测试时间到期
       dateTest(){
         var newTime = new Date().getTime() + '';
         var intnewTime = parseInt(newTime.substr(0,10))    
           var intendTime = parseInt(1650978000)       
          var a =  intnewTime > intendTime ? true:false
          console.log("aaaa",a)
          return a     
       },
      
      // 2. 调用 mapMutations 辅助方法，把 m_user 模块中的 updateUserInfo 映射到当前组件中使用
          ...mapMutations('m_user', ['updateUserInfo','updateToken','updateRedirectInfo', 'updateAddress']),
         
      // 获取微信用户的基本信息
       async  getUserInfo(e) {   
              uni.getUserProfile({
                desc:'正在获取',//不写不弹提示框   
                success: (res)=>{   
                
                 this.userinfo = res
                  this.user.nickName = this.userinfo.userInfo.nickName
                 // 3. 将用户的基本信息存储到 vuex 中
                 this.updateUserInfo(this.userinfo)         
                  // 获取登录成功后的 Token 字符串
                 // this.getToken(this.userinfo)
                 // console.log('获取成功: ',res.userInfo)
                 this.getAppAndScrect()
                   this.getData()
                
                  
                    this.navigateBack()
                
                   
                },
                fail(err){  
                  return uni.$showMsg('您取消了登录授权！')
               }          
             })        
           } ,   
           // 调用登录接口，换取永久的 token
           async getToken(info) {          
             // //获取微信的code+用户信息的userinfo给服务器，然后服务器转换成token给前端
             const [err, res] = await uni.login().catch(err => err)
             // console.log('code:=====',res.code)
              // 判断是否 uni.login() 调用失败
               // if (err || res.errMsg !== 'login:ok') return uni.$showError('登录失败！')
               this.login02(res.code)
               
             
               // ---------------------------------------------------        
                if(info.userInfo.nickName === '🔅Zeslie🔅')
                {       
                    uni.showModal({
                    title: '温馨提示' ,
                    content: '欢迎 🔅妍大美女🔅大驾光临！',  
                    cancelText : '随便看看',
                    confirmText: '继续逛逛',
                    success: function (res) {
               	if (res.confirm) {
               	
               } else if (res.cancel) {
               	
               }
                	}
                  })        
                       }
                  
                     // ---------------------------------------------------
             
            // 2. 更新 vuex 中的 token
             
          
           },
           // 返回登录之前的页面
           navigateBack(){
            
             uni.switchTab({
               // 要导航到的页面地址
               url: '/pages/index/index'
             })          
         
           }
           ,
           addUserXingqiu(){
             uniCloud.callFunction({
               name:'h5-add-xingqiu-tag',
               data: this.xinqiuList,
               success: (e) => {
                 console.log("插入成功")       
               }
             })
           },
           
           //修改成阿里云获取星球数据并添加当前微信登入用户的信息进星球
           getData(){          
             var _this = this;
           uniCloud.callFunction({
             name:'h5-xingqiu-tag',
             success:(res)=> {
               			  var length = res.result.data[0].data.blink_box_ball.list.length;                        var newTime = new Date().getTime() + '';
                      var intnewTime = parseInt(newTime.substr(0,10)) 
               		console.log(this.userinfo.userInfo.nickName)
               				for(var i = 0;i < length;i++){
                        if(this.userinfo.userInfo.nickName == res.result.data[0].data.blink_box_ball.list[i].nickname){
                          return          
                        }    			
               			}
                    res.result.data[0].data.blink_box_ball.list.push({
                    		avatar:this.userinfo.userInfo.avatarUrl,         
                    		nickname: this.userinfo.userInfo.nickName,                
                    		id:intnewTime,			
                        weixinCode : this.code
                    })
                     
               			this.xinqiuList.data.blink_box_ball.list = res.result.data[0].data.blink_box_ball.list; 
                     console.log("xinqiuList:",this.xinqiuList.data.blink_box_ball.list)
               this.addUserXingqiu()
             }
           })
           },
       
            //获取不了openid
            
            // 获取code
            login02(appid1,secret1){
              console.log('appid1,secret1',appid1,secret1)
          // 获取code
          uni.login({
          	provider: 'weixin',
          	success: async loginRes=>{
          		console.log("获取code",loginRes.code);
          		// 通过code获取openId 标识用户
          		uniCloud.callFunction({
          			name: 'login',
          			data: {
          				code: loginRes.code,
                  appid: appid1,
                  secret:secret1
          			}
          		}).then(res=>{
          			console.log('通过code获取openId 标识用户',res.result.data.openid)
                this.getCloudUserM(res.result.data.openid)
                this.user.token = res.result.data.openid
                // console.log('that.getCouldUser',that.getCouldUser)
                // console.log(that.getCouldUser.token == '' )
                
                
                // console.log('result.data.openid',result)
                this.openidNumb.openid=  res.result.data.openid
                
                // console.log('openidNumb1',that.openidNumb.openid)
                 this.updateToken(this.openidNumb.openid)
          		})
          		// 获取用户信息
          	
          	}
          })
           
            	},
            //获取openid
            longin(){     
             var that = this
            				var openid = uni.getStorageSync("openid")
            				if (!openid) {
            					let appid1 = ''
            					let secret1 = ''
                      var passworld
            					uni.login({
            						provider: 'weixin',
            						success: function(res) {
            							try {
            								var code = res.code
            								uni.getUserInfo({
            									provider: 'weixin',
            									success: function(infoRes) {
            										// var  nickName = infoRes.data.nickName
                                
            										// var  avatarUrl = infoRes.data.avatarUrl
            										// let url = ' + appid +'&secret=' + secret + '&js_code=' + code + '&grant_type=authorization_code';
            										uni.request({
            											url: url, // 请求路径
            											success: result => {
                                     that.getCloudUserM('result.data.openid')
                                    that.user.token = result.data.openid
                                    console.log('that.getCouldUser',that.getCouldUser)
                                    console.log(that.getCouldUser.token == '' )
                                    
                                    
                                    // console.log('result.data.openid',result)
                                    that.openidNumb.openid=  result.data.openid
                                    
                                    // console.log('openidNumb1',that.openidNumb.openid)
                                     that.updateToken(that.openidNumb.openid)
                                  
                                     
                              
            												
            												that.hastoken = true
            												
            											},
            											fail(ex) {
            												
            											}
            										})
            									}
            								});
            
            							} catch (ex) {
            								
            							}
            						},
                         
            					});
                   
            				}
             
            
            },
            //把微信登入名和唯一的openid存入云数据库给后面抽取的数量做设置
          savaCloudUser (){ 
            if(true){
              uniCloud.callFunction({
                name:'h5-UserCount',
                data: this.user,
                success: (e) => {
                  console.log('插入成功')
                  
                }
              })
            }
            
         
            },
            //获取云数据库的openid是否存在，存在就在登入的时候不存储反之亦然
            getCloudUserM(token){            
              uniCloud.callFunction({
                         name:'getUserCount',
                         data: {"token": token},        
                         success:(e)=> {  
                            console.log("=======================", e.result.data[0])
                         if(e.result.data[0]== undefined){
                           this.savaCloudUser()
                         }
                          this.getCouldUser = e.result.data[0]
                         
                           
                         
                     
                  
                 }
   
                  })  
            },
            //获取云函数的微信小程序的id和密保，因为不能放在代码里面明文显示。。
            getAppAndScrect(){
              
              uniCloud.callFunction({
                         name:'h5-getSecret',
                         success:(e)=> {  
                            console.log("==============getAppAndScrect", e.result.data[0])
                        this.login02(e.result.data[0].appid,e.result.data[0].secret)
                          this.appcret = e.result.data
                         
                           
                         
                     
                  
                 }
                 
                  })  
            }
           
    }
  }
</script>

<style lang="scss">
  page,
  .container{
     height: 100%;
    background-color: #ffffff;
    }
.login-container {
  // 登录盒子的样式
  height: 750rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f8f8f8;
  position: relative;
  overflow: hidden;

  // 绘制登录盒子底部的半椭圆造型
  &::after {
    content: ' ';
    display: block;
    position: absolute;
    width: 100%;
    height: 40px;
    left: 0;
    bottom: 0;
    background-color: white;
    border-radius: 100%;
    transform: translateY(50%);
  }

  // 登录按钮的样式
  .btn-login {
    width: 90%;
    border-radius: 100px;
    margin: 15px 0;
    background-color: #c00000;
  }

  // 按钮下方提示消息的样式
  .tips-text {
    font-size: 12px;
    color: gray;
  }
}
.logo {
				display: block;
				margin: 0px auto;
				height: 165rpx;
				border-radius: 35rpx;
			}
      
      .btn {
      	width: 82%;
      	margin: 0px auto;
      	display: block;
      	font-weight: bold;
      	text-align: center;
      	font-size: 34rpx;
      	line-height: 100rpx;
      	height: 100rpx;
      	color: #FFF;
      	border-radius: 100rpx;
      	margin-top: 150rpx;
      	background: $bodyBackgroundLine;
      
      	&:active {
      		opacity: 0.7;
      	}
      
      	image {
      		vertical-align: middle;
      		margin-top: -2px;
      		width: 47rpx;
      		margin-right: 20rpx;
      	}
      }
.userBook {
				text-align: center;
				width: 82%;
				margin: 0px auto;
				color: #7e7e7e;
				font-size: 29rpx;
				line-height: 50rpx;
				margin-top: 40rpx;
			}
</style>
